package com.javasea.mq.ack.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasea.mq.ack.entity.BrokerMessageLog;
import com.javasea.mq.ack.entity.Order;
import com.javasea.mq.ack.mapper.BrokerMessageLogMapper;
import com.javasea.mq.ack.mapper.OrderMapper;
import com.javasea.mq.ack.service.BrokerMessageLogService;
import com.javasea.mq.ack.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private BrokerMessageLogService brokerMessageLogService;

    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Override
    public void createOrder(Order order) throws Exception {
        // 使用当前时间当做订单创建时间（为了模拟一下简化）
        LocalDateTime now = LocalDateTime.now();
        order.setId(System.currentTimeMillis());
        // 插入业务数据
        this.save(order);
        // 插入消息记录表数据
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        // 消息唯一ID
        brokerMessageLog.setMessageId(order.getMessageId());
        // 保存消息整体 转为JSON 格式存储入库
        brokerMessageLog.setMessage(JSON.toJSONString(order));
         // 设置消息状态为0 表示发送中
        brokerMessageLog.setStatus("0");
         // 设置消息未确认超时时间窗口为 一分钟
        brokerMessageLog.setNextRetry(now.plusMinutes(1));
        brokerMessageLog.setCreateTime(now);
        brokerMessageLog.setUpdateTime(now);
        brokerMessageLogService.save(brokerMessageLog);
        // 发送消息
        rabbitOrderSender.sendOrder(order);
    }

}
